/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.renren.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.config.ShiroUtils;
import io.renren.dao.SysUserDao;
import io.renren.entity.SysUserEntity;
import io.renren.entity.TokenEntity;
import io.renren.service.SysDeptService;
import io.renren.service.SysUserService;
import io.renren.service.TokenService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysDeptService deptService;

    public void update(SysUserEntity user) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            SysUserEntity userEntity = this.getById(user.getUserId());
            user.setPassword(ShiroUtils.sha256(user.getPassword(), userEntity.getSalt()));
        }
        user.setLoginFailNum(0);
        this.updateById(user);

    }


    @Override
    public SysUserEntity queryByMobile(String mobile) {
        return baseMapper.selectOne(new QueryWrapper<SysUserEntity>().eq("mobile", mobile));
    }

    @Override
    public Map<String, Object> login(SysUserEntity user) {
        SysUserEntity userObj = queryByMobile(user.getMobile());
        Assert.isNull(user, "手机号或密码错误");

        //密码错误
        if(!userObj.getPassword().equals(ShiroUtils.sha256(user.getPassword(), userObj.getSalt()))){
            throw new RRException("手机号或密码错误");
        }

        //获取登录token
        TokenEntity tokenEntity = tokenService.createToken(userObj.getUserId());
        userObj.setDeptName(deptService.getById(userObj.getDeptId()).getName());
        Map<String, Object> map = new HashMap<>(2);
        map.put("token", tokenEntity.getToken());
        map.put("expire", tokenEntity.getExpireTime().getTime() - System.currentTimeMillis());
        map.put("userObj",userObj);
        return map;
    }

}
